﻿package src.com.online.rpg
{
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.geom.ColorTransform;
	import flash.text.TextField;
	import flash.text.TextFormat;
	/**
	 * Stupid Sample Game
	 * ------------------
	 * Collect the hearts while avoiding the enemies!
	 */
	public class SampleGame extends Game
	{
		private var _player:Player;
		private var _heart:GameObject;
		private var _enemies:Vector.<Enemy>;
		private var _score:uint;
		private var _scoreText:TextField;
		private var _test:Boolean;
				
		public override function initialize():void
		{
			super.initialize();
						
			var background:Sprite = new Background();
			addChild(background);
			background.transform.colorTransform = new ColorTransform(0.5, 0.5, 0.5, 1);
		
			_scoreText = new TextField();
			addChild(_scoreText);
			_scoreText.x = _scoreText.y = 5;
			_scoreText.defaultTextFormat = new TextFormat(null, 14, 0xffffff, true);
			
			initLife();
		}
		
		public function initLife():void
		{
			// cleanup old enemies
			for each(var e:Enemy in _enemies)
				removeObject(e);
				
			_enemies = new Vector.<Enemy>;
			
			spawnPlayer();
			spawnHeart();
			
			_score = 0;
			turbo = 1;
		}
		
		public function spawnPlayer():void
		{
			if (_player)
				removeObject(_player);

			_player = new Player;
			addObject(_player);
			_player.x = 200;
			_player.y = 200;
			_player.addEventListener(GameEvent.PLAYER_DIED, onPlayerDied);
		}
				
		private function spawnHeart():void
		{
			// clear previous heart
			if (_heart)
				removeObject(_heart);

			var heart:GameObject = new GameObject(new Heart);
			
			heart.x = Math.random() * (gameWidth - 20) + 10;
			heart.y = Math.random() * (gameHeight - 20) + 10;
			
			_heart = heart;
			
			addObject(heart);
		}
		
		private function spawnEnemy():void
		{
			var e:Enemy = new Enemy();
			addObject(e);
			e.x = Math.random() * gameWidth;
			e.y = Math.random() * gameHeight;
			
			_enemies.push(e);
		}
		
		public override function update(dt:Number):void
		{
			super.update(dt);
			
			if (_heart && _heart.hitTest(_player))
			{
				// heart picked up
				_score++;
				spawnHeart();
				spawnEnemy();
				turbo += 0.02;
			}
			
			// enemy collision
			for each(var e:Enemy in _enemies)
			{
				if (e.active && _player.hitTest(e))
				{
					_player.die();
				}
			}
			
			_scoreText.text = "Score: " + _score.toString();
		}
		
		private function onPlayerDied(e:Event):void
		{
			initLife();
		}
	}

}